package com.aco.party.web.controller.system;

import com.aco.party.enums.MetaTypeEnum;
import com.aco.party.model.po.Dict;
import com.aco.party.model.po.Meta;
import com.aco.party.model.vo.DictParam;
import com.aco.party.model.vo.DictVo;
import com.aco.party.model.vo.common.DataGridEntry;
import com.aco.party.model.vo.common.Page;
import com.aco.party.model.vo.common.PageParam;
import com.aco.party.model.vo.common.Response;
import com.aco.party.service.system.DictService;
import com.aco.party.service.system.MetaService;
import com.aco.party.web.command.system.EditDictCommand;
import com.aco.party.web.validator.system.EditDictValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.aco.party.util.WebModelUtil.*;
/**
 * Created by flying on 3/10/2016 0010.
 */
@Controller
@RequestMapping("/system")
public class ManageDictController extends BaseController {
    Logger logger = LoggerFactory.getLogger(ManageDictController.class);

    @Resource
    private DictService dictService;

    @Resource
    private MetaService metaService;

    private EditDictValidator validator = new EditDictValidator();

    private final String REDIRECTEDIT = "redirect:edit";

    @RequestMapping(value = {"/dict", "/dict/list"}, method = RequestMethod.GET)
    public String showManagePage(HttpServletResponse response,Model model) {
        List<Meta> metas = metaService.getByType(MetaTypeEnum.词条类目.getValue());
        model.addAttribute("cats",metas);
        return "system/manageDicts";
    }

    @RequestMapping(value = "dict/list", method = RequestMethod.POST)
    @ResponseBody
    public Page
            <DictVo> getListJson(HttpServletRequest request, DataGridEntry entry,DictParam param) {
        Page <DictVo> page = new Page<>();
        entry.webParamConvert();
        List <DictVo> list = dictService.getByPage(new PageParam(entry.getOffset(), entry.getLimit()),param);
        page.setTotal(dictService.getTotal(param));
        page.setRows(list);
        return page;
    }

    @RequestMapping(value = "/dict/edit", method = RequestMethod.GET)
    public String showEdit(HttpServletResponse response,@ModelAttribute EditDictCommand command, Model model) {
        if (command.getId() != null) {
            Dict po = dictService.getByPrimaryKey(command.getId());
            if (po != null)
                command.toCommand(po);
            else
                model.addAttribute("no_obj", true);
        }
        setAtt(model);
        return "system/editDict";
    }

    @RequestMapping(value = "/dict/edit", method = RequestMethod.POST)
    public String edit(Model model, @ModelAttribute EditDictCommand command, BindingResult errors) {
        validator.validate(command, errors);
        setAtt(model);
        if (!errors.hasErrors()) {
            Dict dict = new Dict();
                command.toPo(dict);
            dict.setUpdateTime(new Date());
            dictService.update(dict);
            model.addAttribute("no_error",true);
        }
        return "system/editDict";
    }

    @RequestMapping(value = "/dict/add", method = RequestMethod.GET)
    public String showAdd(Model model,@ModelAttribute EditDictCommand command) {
        command.setStatus(1);
        setAtt(model);
        return "system/editDict";
    }

    @RequestMapping(value = "/dict/add", method = RequestMethod.POST)
    public String add(Model model, @ModelAttribute EditDictCommand command, BindingResult errors,RedirectAttributes attributes) {
        validator.validate(command, errors);
        setAtt(model);
        if (errors.hasErrors()) {
            return "system/editDict";
        }
        Dict dict = new Dict();
        command.toPo(dict);
        dict.setCreateTime(new Date());
        dict.setUpdateTime(new Date());
        dictService.add(dict);
        attributes.addAttribute("id",dict.getId());
        attributes.addFlashAttribute("no_error",true);
        return REDIRECTEDIT;
    }

    @RequestMapping(value = "/dict/delete",method = RequestMethod.POST)
    @ResponseBody
    public Response del(@RequestParam(required = true) Long id){
        logger.info("删除：" + id);
        dictService.delete(id);
        return new Response();
    }

    private void setAtt(Model model){
        model.addAttribute("cats", convert2Pairs(metaService.getByType(MetaTypeEnum.词条类目.getValue())));
    }

}
